﻿using System;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using System.Xml.Linq;

namespace GoogleReaderToDelicious.Core.Helpers
{
    //20-Nov-2011 Priyan R
    public class DeliciousHelper
    {
       
        public void AddBookmark(string title, string url, string tags, DateTime date)
        {
            string serviceUrl = "https://api.del.icio.us/v1/posts/add";
            NameValueCollection postData = new NameValueCollection();
            postData.Add("url", url);
            postData.Add("description", title);
            postData.Add("tags", tags);
            postData.Add("dt", date.ToString("yyyy-MM-ddTHH:mm:ssZ"));
            postData.Add("shared", "no");
            try
            {
                string res = GetData(serviceUrl, postData);
                var doc = XDocument.Parse(res);
                var respCode = doc.Descendants("result").First().Attribute("code").Value;
                if (respCode != "done")
                {
                    throw new Exception("Invalid server response :" + respCode);
                }
            }
            catch
            {
                throw;
            }
        }
        String GetData(String url, NameValueCollection postParms)
        {
            String responseText;
            WebRequest webReq;
            StringBuilder postData = new StringBuilder();
            Stream inStream;
            StreamReader outStream;
            WebResponse webResponse;
            byte[] postBytes;
            //create post data
            foreach (string key in postParms.AllKeys)
            {
                if (postData.Length != 0)
                {
                    postData.Append("&");
                }
                var value = postParms[key];
                postData.Append(key + "=" + HttpUtility.UrlEncode(value));
            }
            postBytes = System.Text.Encoding.UTF8.GetBytes(postData.ToString());
            //            
            webReq = WebRequest.Create(url);
            webReq.Method = "POST";
            webReq.ContentType = "application/x-www-form-urlencoded";
            webReq.ContentLength = postBytes.Length;
            webReq.Credentials = new NetworkCredential(UserName, Password);
            inStream = webReq.GetRequestStream();
            inStream.Write(postBytes, 0, postBytes.Length);
            inStream.Close();
            webResponse = webReq.GetResponse();
            outStream = new StreamReader(webResponse.GetResponseStream(), System.Text.Encoding.UTF8);
            responseText = outStream.ReadToEnd();
            outStream.Close();
            return responseText;

        }

        public string UserName { get; set; }
        public string Password { get; set; }

    }
}
